/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.murillo.chufa.datastructures;
import java.util.HashMap;
import java.util.LinkedList;

/**
 *
 * @author Administrador
 */
public class FifoBoundedBag<K> extends BoundedBag<K> {

    HashMap<K, Counter> ocurrenceMap;
    LinkedList<K> valueList;

    public FifoBoundedBag(int maxsize) {
        super(maxsize);
        this.ocurrenceMap = new HashMap<K, Counter>(maxsize / 2);
        this.valueList = new LinkedList<K>();
    }

    @Override
    public void remove(K k) {
        Counter c = ocurrenceMap.get(k);
        if (c != null) {
            int count = c.remove();
            if (count <= 0) {
                ocurrenceMap.remove(k);
            }
            valueList.removeLastOccurrence(k);
        }
    }

    public void add(K k) {
        if (valueList.size() >= maxsize) {
            K last = valueList.getLast();
            remove(last);
        }
        Counter c = ocurrenceMap.get(k);
        if (c == null) {
            c = new Counter();
        }
        c.add();

        valueList.add(k);
    }

    public boolean contains(K k) {
        return ocurrenceMap.containsKey(k);
    }

    @Override
    public void clear() {
        ocurrenceMap.clear();
        valueList.clear();
    }
}
